/************************************************************
 *  * CWSwift CONFIDENTIAL
 * __________________
 * Copyright (C) 2013-2014 CWSwift Technologies. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of CWSwift Technologies.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from CWSwift Technologies.
 * knight lu 349919133
 */

#import "Tools.h"
#import "GTMBase64.h"
#include <CommonCrypto/CommonCryptor.h>

@implementation Tools

#pragma mark - 验证手机号码
+ (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    //    手机号码输入成功
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        
        return YES;
    }
    else
    {
 
        return NO;
    }
}


#pragma mark 删除文件
+ (void)removeFile:(NSString *)fileName
{
    if ([self checkFileExist:fileName])
    {
        //创建文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        //更改到待操作的目录下
        [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
        
        //创建文件fileName文件名称，contents文件的内容，如果开始没有内容可以设置为nil，attributes文件的属性，初始为nil
        [fileManager removeItemAtPath:fileName error:nil];
    }
}

#pragma mark 判断文件是否存在
//判断文件是否存在
+ (BOOL)checkFileExist:(NSString *)photoImagePath
{
    BOOL fileExist = NO;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    if (!documentsDirectory)
    {
        NSLog(@"Documents directory not found!");
    }
    
    NSString* pathToFile = [documentsDirectory stringByAppendingPathComponent:photoImagePath];
    if([[NSFileManager defaultManager] fileExistsAtPath:pathToFile])
    {
        NSLog(@"File is found");
        fileExist = YES;
    }
    
    return fileExist;
}
#pragma mark 获得拍摄照片的文件路径
//获得拍摄照片的文件路径
+ (NSString *)getImageFilePath:(NSString*)photoImagePath
{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    NSString* pathToFile = [documentsDirectory stringByAppendingPathComponent:photoImagePath];
    return pathToFile;
}

+ (void)setValue:(id)value forKey:(NSString *)key
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:value forKey:key];
    [defaults synchronize];
}

+ (NSString *) getValueForKey:(NSString *)key
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *result = [defaults stringForKey:key];
    return result;
}

+ (void) removeForKey:(NSString *)key
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:key];
    [defaults synchronize];
}

//生成驾讯通JXTclientID
+ (NSString *)getCWclientID
{
    NSString *currentDate = [Tools getCurrentSystemTime]; //获得当前日期
    
    NSString *randomNumber1 = [Tools getRandomNumber:100000 to:1000000]; //100W以内的随机数
    
    NSString *randomNumber2 = [Tools getRandomNumber:100000 to:1000000]; //100W以内的随机数
    
    NSString *clientId = [NSString stringWithFormat:@"iosCW%@%@%@", currentDate, randomNumber1, randomNumber2];
    
    return clientId;
}

+ (BOOL)isLogin
{
    NSString *userId = [self getValueForKey:KuserId];
    NSString *password = [self getValueForKey:Kpassword];
    BOOL isLogin = [(NSNumber *)[self getValueForKey:KisLogin] boolValue];
    
    if (isLogin && userId.length && password.length)
        return YES;
    else
        return NO;
}

+ (void)removeUserData
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
//    [defaults removeObjectForKey:KuserId];
//    [defaults removeObjectForKey:Kpassword];
//    [defaults removeObjectForKey:KUID];
    [defaults removeObjectForKey:KisLogin];
    
    [defaults synchronize];
}

+ (NSString *)getRandomNumber: (int)from to:(int)to
{
    NSString *str = [NSString stringWithFormat:@"%d", (int)(from + (arc4random() % (to - from + 1)))];
    return str;
}


+ (NSString *)getCurrentSystemTime
{
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];

    [dateformatter setDateFormat:@"YYYYMMddHHmmss"];
    NSString * morelocationString=[dateformatter stringFromDate:senddate];
    
    return morelocationString;
}

+ (NSString *)timeSpToTime:(NSString *)timeSp
{
    NSTimeInterval timeInterval = [timeSp doubleValue];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *theday = [NSDate dateWithTimeIntervalSince1970:timeInterval];
 
    return [NSString stringWithFormat:@"%@", [dateFormatter stringFromDate:theday]];
}

+ (NSString *)getDateFromStr : (NSString *)timeSp rang:(NSRange)range unit:(NSString *) unit
{
   // "yyyy-MM-dd HH:mm:ss"
    return [NSString stringWithFormat:@"%@%@",[timeSp substringWithRange:range],unit];

}
@end

@implementation NSString(DES)
+ (NSString *) encryptUseDES:(NSString *)str
{
    NSString *key = DES_KEY;
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          [key UTF8String],
                                          kCCKeySizeDES,
                                          nil,
                                          [data bytes],
                                          [data length],
                                          buffer,
                                          1024,
                                          &numBytesEncrypted);
    
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData *dataTemp = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        plainText = [GTMBase64 stringByEncodingData:dataTemp];
    }else{
        NSLog(@"DES加密失败");
    }
    return plainText;
}

+ (NSString *)encodeToPercentEscapeString:(NSString *)input
{
    // Encode all the reserved characters, per RFC 3986
    
    // (<http://www.ietf.org/rfc/rfc3986.txt>)
    
    NSString *outputStr = (NSString *)
    
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            
                                            (CFStringRef)input,
                                            
                                            NULL,
                                            
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            
                                            kCFStringEncodingUTF8));
    
    return outputStr;
}
@end

@implementation UILabelStrikeThrough
@synthesize isWithStrikeThrough;
- (void)drawRect:(CGRect)rect
{
    if (isWithStrikeThrough)
    {
        CGContextRef c = UIGraphicsGetCurrentContext();
        
        CGFloat black[4] = {0.0f, 0.0f, 0.0f, 1.0f};
        CGContextSetStrokeColor(c, black);
        CGContextSetLineWidth(c, 2);
        CGContextBeginPath(c);
        
        //斜线
        //CGContextMoveToPoint(c, rect.origin.x, rect.origin.y+5 );
        //CGContextAddLineToPoint(c, (rect.origin.x + rect.size.width)*0.5, rect.origin.y+rect.size.height-5);
        
        //画斜线
        CGFloat halfWayUp = (self.bounds.size.height - self.bounds.origin.y) / 2.0;
        CGContextMoveToPoint(c, self.bounds.origin.x, halfWayUp );
        CGContextAddLineToPoint(c, self.bounds.origin.x + self.bounds.size.width, halfWayUp);
        CGContextStrokePath(c);
    }
    
    [super drawRect:rect];
}
@end


@implementation UIAlertView(alertView)
+ (void) quickAlert:(NSString *)title withMessage:(NSString *)message{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alertView show];
}
@end